package com.cheney.mapboxexample.common;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;

import androidx.core.app.ActivityCompat;

/**
 * @author CHENEY
 * @date 2022/3/21
 */
public class PermissionUtil {
    private static final String TAG = "PermissionUtil";

    public static final int REQUEST_CODE_USER_LOCATION = 101;

    public static final String[] PERMISSIONS_USER_LOCATION = {
            "android.permission.ACCESS_COARSE_LOCATION",
            "android.permission.ACCESS_FINE_LOCATION"
    };

    /**
     * 若没有权限则发起权限申请
     * @param context 响应请求回调事件页面context
     * @param permissionList 权限列表
     * @param REQUEST_CODE 请求标识
     * @return 申请前是否已有权限
     */
    public static boolean verifyPermissions(Context context, String[] permissionList, int REQUEST_CODE) {
        // 缺少权限，弹出对话框申请权限
        if (!isPermissionGranted(permissionList)) {
            ActivityCompat.requestPermissions((Activity) context, permissionList, REQUEST_CODE);
            return false;
        }
        // 已有权限
        return true;
    }

    /**
     * 判断是否以获得权限
     * @param permissionList 权限列表
     */
    public static boolean isPermissionGranted(String[] permissionList) {
        if (permissionList == null || permissionList.length <= 0){
            return true;
        }
        try {
            boolean isAllGranted = true;
            for (String permission : permissionList) {
                int result = ActivityCompat.checkSelfPermission(MyApplication.getContext(), permission);
                if (result != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }
            return isAllGranted;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
